import React, {Component} from 'react'
import {ADD,MINUS} from './../redux/types'
import {createStore} from './../redux/redux'
import reducer from './../redux/reducers'
let store = createStore(reducer);
//add方法,minus方法就称为action creator
function add(amount) {
    return {type:ADD, amount};
}
function minus(amount) {
    return {type: MINUS, amount};
}

class Counter extends Component {
    constructor() {
        super();
        //用仓库里的初始状态来初始化组件的内部本地状态
        this.state = {number: store.getState().counter.number};
    }

    componentWillMount() {
        //订阅
        this.unsubscribe = store.subscribe(() => {
            this.setState({number: store.getState().counter.number});
        })
    }

    componentWillUnmount() {
        //取消订阅
        this.unsubscribe();
    }

    handleAdd = () => {
        // store.dispatch({type:ADD,amount:2})
        //换成action creater
        store.dispatch(add(2));
    };
    handleMin = () => {
        //store.dispatch({type:MINUS,amount:2})
        //换成action creater
        store.dispatch(minus(2));
    };

    render() {
        return (
            <div >
                <button onClick={this.handleAdd}>+</button>
                <span>{this.state.number}</span>
                <button onClick={this.handleMin}>-</button>
            </div>
        )
    }
}

export default Counter